/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.cvut.fel.taskpro.business.support;

import cz.cvut.fel.taskpro.business.isupport.IBusinessRuleValidator;
import cz.cvut.fel.taskpro.business.isupport.IEnviromentBusiness;
import cz.cvut.fel.taskpro.data.entity.SystemEnviroment;
import cz.cvut.fel.taskpro.data.imanager.IEnviromentData;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.*;
import javax.annotation.PostConstruct;
import javax.annotation.security.DeclareRoles;
import javax.annotation.security.RolesAllowed;
import javax.ejb.EJB;
import javax.ejb.Singleton;
import javax.inject.Inject;
import jxl.JXLException;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

/**
 * This class implement #{@link IEnviromentBusiness} interface
 * @author Tom
 * @version 1.0.0. beta
 */
@DeclareRoles({"admin", "kantor", "student"})
@Singleton
public class EnviromentBusiness implements IEnviromentBusiness, Serializable {

    @EJB
    private IBusinessRuleValidator validator;
    @Inject
    private IEnviromentData enviromentData;
    private Map<String, String> currSeting;
    private List<SystemEnviroment> tomSet;

    @PostConstruct
    public void init() {
        tomSet = enviromentData.getAllEnviroments();
        currSeting = new HashMap<String, String>();
        Iterator sysIt = tomSet.iterator();
        while (sysIt.hasNext()) {
            SystemEnviroment currEnv = (SystemEnviroment) sysIt.next();
            currSeting.put(currEnv.getKeyOfSetting(),
                    currEnv.getValueOfSetting());
        }
    }

    @Override
    public List<SystemEnviroment> getAllEnviromentSetting() {
        return tomSet;
    }

    @Override
    public String getValueOfEnviroment(String keyOfValue) {
        String value = currSeting.get(keyOfValue);
        return value;
    }

    @RolesAllowed("admin")
    @Override
    public void addEnviroment(SystemEnviroment enviroment) throws BusinessRuleException {
        validator.validateAddingEnvriroment(enviroment);
        enviromentData.addSystemEnviroment(enviroment);
    }

    @RolesAllowed("admin")
    @Override
    public void addEnviroment(List<SystemEnviroment> enviroments) throws BusinessRuleException {
        validator.validateAddingEnvriroment(enviroments);
        Iterator envIt = enviroments.iterator();
        while (envIt.hasNext()) {
            enviromentData.addSystemEnviroment((SystemEnviroment) envIt.next());
        }
        refresh();
    }

    @RolesAllowed("admin")
    @Override
    public List<SystemEnviroment> importEnviroment(File fileWithSetting) throws TaskProException {
        List<SystemEnviroment> enviroments = new ArrayList<SystemEnviroment>();
        Workbook workbook = null;
        try {
            workbook = Workbook.getWorkbook(fileWithSetting);
            Sheet sheet = workbook.getSheet(0);
            //prvni je slupec druhy je radek
            int radek = 0;
            while (true) {
                sheet.getCell(0, radek).getContents();
                SystemEnviroment newEnviroment = createEnviroment(sheet.getCell(0, radek).getContents(),
                        sheet.getCell(1, radek).getContents(),
                        sheet.getCell(2, radek).getContents());
                if (newEnviroment == null) {
                    break;
                }
                enviroments.add(newEnviroment);
                radek++;
            }
        } catch (IOException ex) {
            throw new TaskProException(90, "IOException has occured during reading file" + fileWithSetting.getAbsolutePath());
        } catch (BiffException ex) {
            throw new TaskProException(90, "BiffException has occured during reading file" + fileWithSetting.getAbsolutePath());
        } catch (JXLException e) {
            workbook.close();
        } catch (Exception e) {
            workbook.close();
        }
        return enviroments;
    }
    /**
     * This method create construct a new system enviroment.
     * @param description 
     * @param key 
     * @param value 
     * @return new enviroment object
     */
    private SystemEnviroment createEnviroment(String key, String value, String description) {
        SystemEnviroment newEnviroment = new SystemEnviroment();
        if (("".equals(key)) && ("".equals(value)) && ("".equals(description))) {
            return null;
        }
        newEnviroment.setDescription(description);
        newEnviroment.setKeyOfSetting(key);
        newEnviroment.setValueOfSetting(value);
        return newEnviroment;
    }

    @RolesAllowed("admin")
    @Override
    public void updateEnviroments(List<SystemEnviroment> enviroment) throws BusinessRuleException {
        validator.validateModification(enviroment);
        if (enviroment.isEmpty()) {
            return;
        }
        Iterator itEv = enviroment.iterator();
        while (itEv.hasNext()) {
            SystemEnviroment currEnv = (SystemEnviroment) itEv.next();
            if (currEnv.getId() == null) {
                enviromentData.addSystemEnviroment(currEnv);
            } else {
                enviromentData.update(currEnv);
            }
        }
        refresh();
    }

    @RolesAllowed("admin")
    @Override
    public void removeEnviroments(List<SystemEnviroment> enviromentToDelete) {
        if (enviromentToDelete == null) {
            return;
        }
        if (enviromentToDelete.isEmpty()) {
            return;
        }
        Iterator envToDelIt = enviromentToDelete.iterator();
        while (envToDelIt.hasNext()) {
            SystemEnviroment currEnv = (SystemEnviroment) envToDelIt.next();
            if (tomSet.contains(currEnv)) {
                enviromentData.remove(currEnv);
            }
        }
        refresh();
    }

    @RolesAllowed("admin")
    @Override
    public void refresh() {
        init();
    }
}
